package br.com.fiap.mercadinho.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.fiap.mercadinho.bean.User;
import br.com.fiap.mercadinho.common.SessionKey;

/**
 * Filtro utilizado para verifcar se o usuario esta devidamente logado. Caso ele
 * nao esteja logado o filtro redireciona para a pagina de login
 */
@WebFilter("/*")
public class AuthenticatorFilter implements Filter {

	private static final String LOGIN_URL = "login.jsp";
	private static final String LOGIN_SERVLET = "login";
	public AuthenticatorFilter() {

	}

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		if (!isLoginPage(request) && !isUserLogged(request)) {
			redirectToLogin(response);
		} else {
			chain.doFilter(request, response);
		}

	}

	/**
	 * Verifica se o usuario esta na pagina de login
	 * @param request
	 * @return
	 */
	private boolean isLoginPage(ServletRequest request) {
		HttpServletRequest req = (HttpServletRequest) request;
		return req.getServletPath().endsWith(LOGIN_URL) || req.getServletPath().endsWith(LOGIN_SERVLET);
	}

	/**
	 * Redireciona usario para a tela de login.
	 * @param response
	 * @throws IOException
	 */
	private void redirectToLogin(ServletResponse response) throws IOException {
		HttpServletResponse resp = (HttpServletResponse) response;
		resp.sendRedirect(LOGIN_URL);
	}

	/**
	 * Verifica se existe um usuario logado na aplicacao
	 * 
	 * @param request
	 * @return
	 */
	private boolean isUserLogged(ServletRequest request) {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		User userLogged = (User) session
				.getAttribute(SessionKey.USER_SESSION_KEY.getValue());
		boolean isUserLogged = userLogged != null;
		return isUserLogged;
	}

	public void init(FilterConfig fConfig) throws ServletException {

	}

}
